from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from src.database.services import CalendarService, SubscriptionService


async def calendars_getter(
    dialog_manager: DialogManager, calendar_service: CalendarService, **kwargs
):
    category_id: int = dialog_manager.dialog_data.get("category_id")
    calendars = await calendar_service.get_calendars_in_category(category_id)

    return {
        "calendars": calendars,
    }


async def user_calendars_getter(
    dialog_manager: DialogManager, calendar_service: CalendarService, **kwargs
):
    user_id: int = dialog_manager.event.from_user.id
    user_calendars = await calendar_service.get_user_calendars(user_id)

    return {
        "user_calendars": user_calendars,
    }


async def calendar_details_getter(
    dialog_manager: DialogManager,
    calendar_service: CalendarService,
    subscription_service: SubscriptionService,
    **kwargs,
):
    locale: TranslatorRunner = dialog_manager.middleware_data.get("locale")
    calendar_id: int = dialog_manager.dialog_data.get("calendar_id")
    user_calendar_id: int = dialog_manager.dialog_data.get("user_calendar_id")

    user_calendar = None
    if user_calendar_id:
        # Получаем информацию о календаре пользователя

        user_subscription = await subscription_service.get_active_user_subscription(
            dialog_manager.event.from_user.id
        )
        user_calendar = await calendar_service.get_user_calendar_by_id(
            user_calendar_id, user_subscription.id
        )
        calendar = await calendar_service.get_calendar_by_id(user_calendar.calendar_id)
    else:
        calendar = await calendar_service.get_calendar_by_id(calendar_id)

    user_lang = locale.translators[0].locale
    calendar_title = getattr(calendar, f"title_{user_lang}", calendar.title_ru)
    calendar_description = getattr(
        calendar, f"description_{user_lang}", calendar.description_ru
    )

    data = {
        "calendar_title": calendar_title,
        "calendar_description": calendar_description,
    }
    if user_calendar:
        data.update(
            {
                "user_calendar_id": user_calendar.id,
                "calendar_title": calendar_title,
                "calendar_description": calendar_description,
                "status": locale.get(user_calendar.status.value),
                "successful_tasks": user_calendar.successful_tasks,
                "total_tasks": len(calendar.tasks),
                "tasks_sent": user_calendar.tasks_sent,
                "get_tasks_time": user_calendar.get_tasks_time.strftime("%H:%M"),
                "check_tasks_time": user_calendar.check_tasks_time.strftime("%H:%M"),
            }
        )

    return data
